import { useState,useEffect } from 'react';
import { Table,Switch,Space,Button,Card,ConfigProvider,Modal,Form, Input,Select,Row,Col,message,Popconfirm  } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import zh_CN from 'antd/es/locale/zh_CN';
import {getMemberListApi,getRoleSelectApi,getAddMemberApi,getEditMemberApi,getDelMemberApi} from '@/api/authority'
const { TextArea } = Input;

interface DataType {
  emplId:number;
  key:number;
  emplNumber: string;
  emplName: string;
  emplPhone: number;
  emplMail: string;
  roleName: string;
  lastTime: string;
  state: number;
}


const data: DataType[] = [];
  for (let i = 0; i < 20; i++) {
      data.push({
        emplId: i+1,
        key: i + 2,
        emplNumber: '张三',
        emplName: 'HJSI48393',
        emplPhone: 4,
        emplMail: '2022-1-2',
        roleName: '2022-1-2',
        lastTime: '2022-1-2',
        state:1
      });
  }

  
function AuthorityManagement() {
  const [roleList,setRoleList] = useState<DataType[]>([])
  const [selectedRow, setSelectedRow] = useState<DataType[]>([]);
  const [memberSelectOption,setMemberSelectOption] = useState([{
    label:'',
    value:''
  }])
  const [openAdd,setOpenAdd] = useState(false)
  const [openEdit,setOpenEdit] = useState(false)
  const [selectForm] = Form.useForm()
  const [addForm] = Form.useForm()
  const [editForm] = Form.useForm()

  const [messageApi, contextHolder] = message.useMessage();


  useEffect(()=>{
    getMemberList()
    getSelectRole()
  },[])
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'key',
    },
    {
      title: '成员账号',
      dataIndex: 'emplNumber',
    },
    {
      title: '姓名',
      dataIndex: 'emplName',
    },
    {
      title: '手机号',
      dataIndex: 'emplPhone',
    },
    {
      title: '邮箱',
      dataIndex: 'emplMail',
    },
    {
      title: '角色',
      dataIndex: 'roleName',
    },
    {
      title: '最近登录时间',
      dataIndex: 'lastTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => (
        <Space size="middle">
          <Button className='edmit' onClick={()=>{editRoleDisplay(record)}}>编辑</Button>
          <Popconfirm
            title="删除该成员"
            description="你真的要删除该成员嘛？"
            okText="删除"
            cancelText="取消"
            onConfirm={()=>{delRole(record)}}
          >
            <Button id='del'>删除</Button>
          </Popconfirm>
        </Space >
      ),
    },
  ];
  //获取成员列表
  const getMemberList= async()=>{
    const {data} = await getMemberListApi()
    let list = data.map((item :any,index:number)=>{
      item.key = index+1
      return item
    })
    setRoleList(list)
  }
  //获取角色列表
  const getSelectRole = async()=>{
    const {data} = await getRoleSelectApi()
    let selectArr = data.map((item:any)=>{
      let obj = {
        label:'',
        value:''
      }
      obj.value = item
      obj.label = item
      return obj
    })
    setMemberSelectOption(selectArr)
  }
  //添加角色 
  const addRole = async(val:any)=>{
    const res =  await getAddMemberApi(val)
    if(~~res.code !== 200){
      messageApi.open({
      type: 'error',
      content: res.msg
      });
      return
    }
    setOpenAdd(false)
    getMemberList()
    addForm.resetFields()
    messageApi.open({
      type: 'success',
      content: '添加成功!'
    });
  }
  // 编辑角色
  const editRoleDisplay = (val:DataType)=>{
    let obj = {
      emplId:0,
      emplMail:'',
      emplName:'',
      emplNumber:'',
      emplPhone:0,
      roleName:''
    }
    obj.emplId  = val.emplId
    obj.emplMail = val.emplMail
    obj.emplName = val.emplName
    obj.emplNumber = val.emplNumber
    obj.emplPhone = val.emplPhone
    obj.roleName = val.roleName
    editForm.setFieldsValue(obj)
    setOpenEdit(true);
  }
  const editRole = async(val:any)=>{
    await getEditMemberApi(val)
    getMemberList()
    setOpenEdit(false)
    messageApi.open({
      type: 'success',
      content: '修改成功!'
    });
    
  }
  //删除角色
  const delRole = async(val:DataType)=>{
    await getDelMemberApi([val.emplId])
    getMemberList()
    messageApi.open({
      type: 'success',
      content: '删除成功!'
    });
  }
  // 批量删除
  const delMore = async()=>{
    const idArr = selectedRow.map((item:DataType)=>item.emplId)
    const res = await getDelMemberApi(idArr)
    if(~~res.code !== 200){
      messageApi.open({
      type: 'error',
      content: res.msg
      });
      return
    }
    getMemberList()
    messageApi.open({
      type: 'success',
      content: '批量删除成功!'
    });
  }
  const rowSelection = {
    onChange:(key :any,row :DataType[])=>{
      setSelectedRow(row)
    },
  }
  //查询成员
 const selectMember = async (val:any)=>{
  
    const {data} = await getMemberListApi(val)
    let list = data.map((item :any,index:number)=>{
      item.key = index+1
      return item
    })
    setRoleList(list)
 }
 //重置
 const reSet = ()=>{
  getMemberList()
  selectForm.resetFields()
 }
 const addCancel = ()=>{
    setOpenAdd(false)
    addForm.resetFields()
 }

    return (
        <div className='AuthorityManagement'>
            <p className="head">成员管理</p>
            {contextHolder}
            <Card title="筛选查询" type="inner" style={{ marginTop:'20px'}}>
            <Form
              name="basic"
              onFinish={selectMember}
              autoComplete="off"
              form={selectForm}
            >
              <Row gutter={24}>
              <Col span={6}>
              <Form.Item
                label="关键词"
                name="keys"        
                style={{width:'100%'}}
              >
                <Input placeholder='成员账号/姓名' />
              </Form.Item>
              </Col>
              <Col span={4}>
              <Form.Item
                label="角色"
                name="roleName"
              >
                <Select
                  placeholder='请选择'
                  style={{ width: 120 }}
                  options={memberSelectOption}
                />
              </Form.Item>
              </Col>
              <Col span={4}>
              <Form.Item>
                <Space>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button type="primary" onClick={reSet}>
                  重置
                </Button>
                </Space>
              </Form.Item>
              </Col>
            </Row>
            </Form>
            </Card>
            <Card title="数据列表" type="inner" style={{ marginTop:'20px'}} extra={<Space>
              <Button onClick={()=>{setOpenAdd(true)}} className='add'>添加</Button>
              {/* <Button onClick={delMore} id='del'>批量删除</Button> */}
              <Popconfirm
                  title="删除该成员"
                  description="你真的要批量删除成员嘛？"
                  okText="删除"
                  cancelText="取消"
                  onConfirm={delMore}
                >
                  <Button id='del'>批量删除</Button>
                </Popconfirm>
            </Space>}>
            <ConfigProvider locale={zh_CN}>
              <Table columns={columns} rowSelection={rowSelection} dataSource={roleList} pagination={{ position: ['bottomCenter'],
              defaultPageSize: 2,
              pageSizeOptions: [2, 5, 10, 15],
              showQuickJumper: true,
              showSizeChanger: true, }}  />
              </ConfigProvider>
            </Card >
            <Modal
              title="添加成员"
              open={openAdd}
              onOk={()=>{addForm.submit()}}
              onCancel={addCancel}
            >
               <Form
                    form = {addForm}
                    name="addForm"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    autoComplete="off"
                    onFinish={addRole}
                  >
                    <Form.Item
                      label="成员账号"
                      name="emplNumber"
                      rules={[{ required: true, message: '输入该角色名称' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="姓名"
                      name="emplName"
                      rules={[{ required: true, message: '输入姓名' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="手机号"
                      name="emplPhone"
                      rules={[{ required: true, message: '输入手机号' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="邮箱"
                      name="emplMail"
                      rules={[{ required: true, message: '输入邮箱' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="角色"
                      name="roleName"
                      rules={[{ required: true, message: '请选择' }]}
                    >
                      <Select
                        placeholder='请选择'
                        style={{ width: 120 }}
                        options={memberSelectOption}
                      />
                    </Form.Item>
                    <Form.Item
                      label="登录密码"
                      name="emplPwd"
                      rules={[{ required: true, message: '输入密码' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="备注信息"
                      name="emplNote"
                    >
                      <TextArea rows={4} maxLength={200} />
                    </Form.Item>
                  </Form>
            </Modal>
            <Modal
              title="编辑成员"
              open={openEdit}
              onOk={()=>{editForm.submit()}}
              onCancel={()=>{setOpenEdit(false)}}
            >
               <Form
                    form = {editForm}
                    name="editForm"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    autoComplete="off"
                    onFinish={editRole}
                  >
                     <Form.Item
                      label="成员id"
                      name="emplId"
                    >
                      <Input disabled />
                    </Form.Item>
                    <Form.Item
                      label="成员账号"
                      name="emplNumber"
                      rules={[{ required: true, message: '输入该角色名称' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="姓名"
                      name="emplName"
                      rules={[{ required: true, message: '输入姓名' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="手机号"
                      name="emplPhone"
                      rules={[{ required: true, message: '输入手机号' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="邮箱"
                      name="emplMail"
                      rules={[{ required: true, message: '输入邮箱' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="角色"
                      name="roleName"
                      rules={[{ required: true, message: '请选择' }]}
                    >
                      <Select
                        placeholder='请选择'
                        style={{ width: 120 }}
                        options={memberSelectOption}
                      />
                    </Form.Item>
                    <Form.Item
                      label="登录密码"
                      name="emplPwd"
                      rules={[{ required: true, message: '输入密码' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="备注信息"
                      name="emplNote"
                    >
                      <TextArea rows={4} maxLength={200} />
                    </Form.Item>
                  </Form>
            </Modal>
        </div>
    )
}

export default AuthorityManagement